package cc.woori.mobile;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import cc.woori.mobile.bean.ChurchServiceEntry2;
import cc.woori.mobile.bean.PodCastEntity;
import cc.woori.mobile.podcast.Category;
import cc.woori.mobile.podcast.EnclosureType;
import cc.woori.mobile.podcast.ImageUrl;
import cc.woori.mobile.podcast.PodCastCategory;
import cc.woori.mobile.podcast.PodCastChannel;
import cc.woori.mobile.podcast.PodCastEnclosure;
import cc.woori.mobile.podcast.PodCastItem;
import cc.woori.mobile.podcast.PodCastOwner;
import cc.woori.mobile.podcast.PodCastRSS;

public class PublishPodCastServlet extends HttpServlet {
    private static final Logger log = Logger
	    .getLogger(PublishPodCastServlet.class.getName());
    /**
     * 
     */
    private static final long serialVersionUID = -9065284626029078732L;
    private static final String ITUNES_DATE_PATTERN = "EEE, d MMM yyyy HH:mm:ss zzz";
    private static final SimpleDateFormat sdf = new SimpleDateFormat(
	    ITUNES_DATE_PATTERN);
    static {
	sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {

	log.info("doGet() - called");
	resp.setContentType("text/xml; charset=UTF-8");
	PrintWriter out = new PrintWriter(new OutputStreamWriter(
		resp.getOutputStream(), "UTF8"), true);

	log.info("Initialize PodCastRss() - ");

	PodCastRSS pcRSS = new PodCastRSS();
	pcRSS.setXmlns("http://www.itunes.com/dtds/podcast-1.0.dtd");
	pcRSS.setVersion(2.0);

	log.info("init JAXB");

	PersistenceManager pm = PMF.get().getPersistenceManager();

	try {

	    log.info("Init PodCastEntity");
	    PodCastEntity pce = null;
	    Extent<PodCastEntity> ext = pm.getExtent(PodCastEntity.class);
	    Iterator<PodCastEntity> iterator = ext.iterator();
	    if (iterator.hasNext()) {
		pce = iterator.next();
	    }
	    if (pce == null) {
		log.warning("pce is null!!!!!!!!!!");
		return;
	    }

	    log.info("init Channel Object");

	    PodCastChannel channel = new PodCastChannel();
	    channel.setAuthor(pce.getAuthor());
	    channel.setCopyright("Woori.cc");
	    channel.setDescription(pce.getDescription());
	    ImageUrl img_url = new ImageUrl();
	    img_url.setHref(pce.getImg_url());
	    channel.setImageUrl(img_url);
	    channel.setLanguage("ko-kr");
	    channel.setLink(pce.getLink());
	    Collection<PodCastCategory> categories = new ArrayList<PodCastCategory>();
	    PodCastCategory pCat = new PodCastCategory();
	    pCat.setText(Category.ReligionAndSpirituality.toString());
	    PodCastCategory subCat = new PodCastCategory();
	    subCat.setText("Christianity");
	    pCat.setCategory(subCat);
	    categories.add(pCat);
	    channel.setCategories(categories);

	    PodCastOwner owner = new PodCastOwner();
	    owner.setEmail(pce.getOwner_email());
	    owner.setName(pce.getOwner());
	    channel.setOwner(owner);
	    channel.setSubtitle(pce.getSubtitle());
	    channel.setSummary(pce.getSummary());
	    channel.setTitle(pce.getTitle());

	    log.info("testing info");
	    Query query = pm.newQuery(ChurchServiceEntry2.class);
	    query.setOrdering("publishDate desc");
	    query.setRange(0, 52);

	    @SuppressWarnings("unchecked")
	    List<ChurchServiceEntry2> results = (List<ChurchServiceEntry2>) query
		    .execute();
	    ArrayList<PodCastItem> itmList = new ArrayList<PodCastItem>();

	    log.info("testing info");
	    for (ChurchServiceEntry2 e : results) {
		PodCastItem vitm = new PodCastItem();
		vitm.setAuthor(e.getAuthor());
		vitm.setKeywords(e.getAuthor());

		vitm.setPubDate(sdf.format(e.getPublishDate()));
		vitm.setDuration("01:00:00");
		vitm.setSubTitle(e.getVerse());

		vitm.setTitle("[Video]" + e.getTitle());
		vitm.setSummary(e.getVerse() + "\n"
			+ e.getDescription().getValue());
		vitm.setGuid(e.getSvcVideoUrl());
		PodCastEnclosure enc = new PodCastEnclosure();
		enc.setUrl(e.getSvcVideoUrl());
		enc.setType(EnclosureType.MP4);
		enc.setLength(1000000);
		vitm.setEnclosure(enc);
		itmList.add(vitm);

		PodCastItem aitm = new PodCastItem();
		aitm.setAuthor(e.getAuthor());
		aitm.setKeywords(e.getAuthor());

		aitm.setPubDate(sdf.format(e.getPublishDate()));
		aitm.setDuration("01:00:00");
		aitm.setSubTitle(e.getVerse());

		aitm.setTitle("[MP3]" + e.getTitle());
		aitm.setSummary(e.getVerse() + "\n"
			+ e.getDescription().getValue());
		aitm.setGuid(e.getSvcAudioUrl());
		enc = new PodCastEnclosure();
		enc.setUrl(e.getSvcAudioUrl());
		enc.setType(EnclosureType.MP3);
		enc.setLength(1000000);
		aitm.setEnclosure(enc);
		itmList.add(aitm);
	    }

	    channel.setItem(itmList);
	    pcRSS.setChannel(channel);

	    Serializer serializer = new Persister();

	    serializer.write(pcRSS, out);
	    log.info("testing info");
	} catch (Exception e) {
	    log.info("exception occured");
	    StackTraceElement[] traces = e.getStackTrace();
	    for (StackTraceElement ste : traces) {
		log.severe(ste.toString());
	    }

	    e.printStackTrace();
	    log.severe(e.getMessage());
	} finally {
	    log.info("closing persistent Manager");
	    pm.close();
	}
	log.info("end of itunes publish servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {
	doGet(req, resp);
    }

}
